<?php
/**
 * Created by IntelliJ IDEA.
 * User: kaireewu
 * Date: 11-10-17
 * Time: 下午4:18
 * To change this template use File | Settings | File Templates.
 */
require_once('inc/common.inc.php');
$act = getgpc('action','P');
switch($act) {
    case 'dopost':
        doPost();
        break;
    case 'login':
        login();
        break;
    case 'reg':
        reg();
        break;
    case 'edit':
        edit();
        break;
    case 'getItem':
        getItem();
        break;
    default:
        paramError();
        break;
}

function getItem(){
    global $logined, $user;
    if(!$logined || !is_array($user)) {
        makeJson('', 1, '您当前没有登录');
        return;
    }
    $sid = trim(urldecode(getgpc('sid', 'P')));

    $code = 0;
    $msg = '';
    $data = array();
    global $db;
    if($db){
        $query = $db->prepare('SELECT sid, uid, url, title, intro, posttime, cid FROM "datas" WHERE sid=:sid');
        $query->bindParam(':sid', $sid, PDO::PARAM_INT);
        $query->execute();
        $data = $query->fetch(PDO::FETCH_ASSOC);
        if(!$data) {
            $code = 1;
            $msg .= '该项目不存在或已被删除，请刷新页面再试。';
        }
    } else {
         $code = 1;
         $msg .= "连接数据库失败，请联系系统管理员。";
    }
    makeJson($data, $code, $msg);
}

function edit() {
    global $logined, $user;

    if(!$logined || !is_array($user)) {
        makeJson('', 1, '您当前没有登录');
        return;
    }
    $upass = trim(urldecode(getgpc('upass', 'P')));
    $repass = trim(urldecode(getgpc('repass', 'P')));
    $nickname = trim(urldecode(getgpc('nickname', 'P')));
    $email = trim(urldecode(getgpc('email', 'P')));
    $url = trim(urldecode(getgpc('url', 'P')));

    $code = 0;
    $msg = '';
    $upass = empty($upass) ? $user['upass'] : $upass;
    if($upass != $user['upass']) {
        if ($upass != $repass) {
            $code = 1;
            $msg .= '两次输入的密码不一致\n';
        }
    }
    $nickname = empty($nickname) ? $user['uname'] : $nickname;

    if(!$code) {
        global $db;
        if($db) {
            $query = $db->prepare('UPDATE "members" SET upass=:upass, nickname=:nickname, email=:email, url=:url WHERE uid=:uid');
            $query->bindParam(':upass', $upass, PDO::PARAM_STR);
            $query->bindParam(':nickname', $nickname, PDO::PARAM_STR);
            $query->bindParam(':email', $email, PDO::PARAM_STR);
            $query->bindParam(':url', $url, PDO::PARAM_STR);
            $query->bindParam(':uid', $user['uid'], PDO::PARAM_INT);
            if($query->execute()) {
                $msg = "修改成功";
                $user['upass'] = $upass;
                $user['nickname'] = $nickname;
                $user['email'] = $email;
                $user['url'] = $url;
                updateUser($user);
            } else {
                $code = 1;
                $msg .= "数据保存失败，请稍候再试。";
            }
        } else {
            $code = 1;
            $msg .= "连接数据库失败，请联系系统管理员。";
        }
    }
    makeJson('', $code, $msg);
}

function reg() {
    $resultBody = '';
    $resultcode = 0;
    $resultmsg = '';
    $uname = trim(urldecode(getgpc('uname', 'P')));
    $upass = trim(urldecode(getgpc('upass', 'P')));
    $repass = trim(urldecode(getgpc('repass', 'P')));
    $nickname = trim(urldecode(getgpc('nickname', 'P')));
    $email = trim(urldecode(getgpc('email', 'P')));
    $url = trim(urldecode(getgpc('url', 'P')));
    // TODO: 数据校验
    $nickname = empty($nickname) ? $uname : $nickname;

    if(empty($uname)){
        $resultcode = 1;
        $resultmsg .= '用户名不能为空\n';
    }
    if(empty($upass)){
        $resultcode = 1;
        $resultmsg .= '密码不能为空\n';
    } else if ($upass != $repass) {
        $resultcode = 1;
        $resultmsg .= '两次输入的密码不一致\n';
    }

    if(!$resultcode){
        if(checkUname($uname, $resultcode, $resultmsg)){
           global $db;
           if($db) {
               $query = $db->prepare('INSERT INTO "members" ("uname", "upass", "email", "nickname", "url") VALUES (:uname, :upass, :email, :nickname, :url);');
               $query->bindParam(':uname', $uname, PDO::PARAM_STR);
               $query->bindParam(':upass', md5($upass), PDO::PARAM_STR);
               $query->bindParam(':email', $email, PDO::PARAM_STR);
               $query->bindParam(':nickname', $nickname, PDO::PARAM_STR);
               $query->bindParam(':url', $url, PDO::PARAM_STR);
               $uid = 0;
               if($query->execute()){
                   $uid = $db->lastInsertId('members');
               }
               if($uid > 0) {
                   global $user;
                   $query = $db->prepare("UPDATE rtx SET registed=1 WHERE rtxid=:rtxid");
                   $query->bindParam(':rtxid', $uname, PDO::PARAM_STR);
                   $query->execute();
                   $query = $db->query("SELECT uid, uname, upass, email, nickname, url FROM members WHERE uid=".$uid);
                   $user = $query->fetch(PDO::FETCH_ASSOC);
                   doLogin($uname, $upass);
                   $resultBody = $user;
                   $resultcode = 0;
                   $resultmsg = "注册成功";
               } else {
                   $resultcode = 1;
                   $resultmsg .= "数据库故障，注册失败\n";
               }
           }
           else {
               $resultcode = 1;
               $resultmsg .= "数据库故障，注册失败\n";
           }
        }
    }
    makeJson($resultBody, $resultcode, $resultmsg);
}

function checkUname($uname, &$code, &$msg) {
    global $db;
    if($db){
        $query = $db->prepare("SELECT rtxid, registed FROM rtx WHERE rtxid=:rtxid");
        $query->bindParam(':rtxid', $uname, PDO::PARAM_STR);
        $query->execute();
        $rtxinfo = $query->fetch(PDO::FETCH_ASSOC);
        if($rtxinfo) {
            if($rtxinfo['registed']) {
                $code = 1;
                $msg .= 'RTX ID已被注册\n';
            } else {
                $code = 0;
                $msg = 'RTX ID检查通过';
            }
        } else {
            $code = 1;
            $msg .= "RTX ID无权注册\n";
        }
    } else {
        $code = 1;
        $msg .= "数据库连接失败，无法注册";
    }
    return !$code;
}

function login() {
    $resultBody = '';
    $uname = $upass = '';
    $uname = trim(urldecode(getgpc('uname')));
    $upass = trim(urldecode(getgpc('upass')));
    if(empty($uname) || empty($upass)){
        makeJson('', 1, '用户名和密码不能为空');
        return;
    }
    if (doLogin($uname, $upass)){
        global $user;
        $resultBody = $user;
        makeJson($resultBody, 0, '登录成功');
    } else {
		makeJson($resultBody, 1, '登录失败');
	}
}

function doPost(){
    global $logined, $user, $db;
    if (!$logined) {
        makeJson('<script type="text/javascript">location.href="login.php";</script>', 1, '用户未登录');
        return;
    }
    $resultBody = '';
    $sid = $title = $url = $category = $content = '';
    $sid = trim(urldecode(getgpc('sid')));
    $title = trim(urldecode(getgpc('addTitle')));
    $url = trim(urldecode(getgpc("addUrl")));
    $category = trim(getgpc('addCategory'));
    $content = dhtmlspecialchars(trim(urldecode(getgpc('addContent'))));
    if($db){
        if(!$sid || $sid == '0') {
            $sql = "INSERT INTO datas (uid, url, title, intro, posttime, cid) VALUES (%d, %s, %s, %s, %s, %d)";
            $sql = sprintf($sql
                       ,$user['uid']
                       ,$db->quote($url)
                       ,$db->quote($title)
                       ,$db->quote($content)
                       ,$db->quote(time())
                       ,$category);
        } else {
            $sql = 'UPDATE "datas" SET url=%s, title=%s, intro=%s, cid=%d WHERE sid=%d';
            $sql = sprintf($sql
                       ,$db->quote($url)
                       ,$db->quote($title)
                       ,$db->quote($content)
                       ,$category
                       ,$sid);
        }
        if($db->exec($sql)){
            //$sid = $sid || $db->lastInsertId("datas");
            //$result = $db->prepare("SELECT m.uid as uid,m.uname as uname,m.QQ as QQ, m.email as email, m.nickname as nickname, d.sid as sid,d.url as url,d.title as title,d.intro as intro,d.posttime as posttime FROM datas AS d INNER JOIN members AS m ON d.uid = m.uid WHERE d.sid=?");
            //$result->execute($sid);
            //$resultBody = $result->fetch(PDO::FETCH_ASSOC);
            makeJson('', 0, '操作成功');
        } else {
            makeJson($sql, 1, '保存失败');
        }
    } else {
        makeJson('', 1, '数据库连接失败');
    }

}

function paramError() {
    makeJson('', 1, '参数错误');
}

function makeJson($body, $code = 0, $msg = ''){
    $result = array(
        'code' => $code,
        'msg' => $msg,
        'body' => $body
    );
    header('content-type:application/json;charset=utf-8');
    echo(json_encode($result));
}
 
